<?php

class session {
	// Class constructor
	// Authorizes users as long as they're not 
	// allready in session or on the banlist 
	public function __construct() {
		if(!$this->inSession()) {
			if(!$this->banlist()) {
				if($_POST['username'] && $_POST['password']) {
					$user = mysql_real_escape_string($_POST['username']);
					$pass = mysql_real_escape_string($_POST['password']);

					$qsql = "SELECT id, user FROM users 
							WHERE username='".$user."'
							AND password = SHA1('".$pass."')";
				
					$result = mysql_query($qsql);
					if(!$result) { 
						die('Invalid query: ' . mysql_error());
					}
				
					if(mysql_num_rows($result) == 1) {
						$this->authorize($user);
						$this->save('login', $user);
						header('Location: ../account/');
					} else {
						$this->unauthorized($user);
						$this->save('failed', $user);
					}
				}
			} else {
				$this->save('banned');
				echo 'Max. login attempts reached';
			}
		}
	}
	
	// Destroys session
	public function logout() {
		if(isset($_SESSION['user']) && $_SESSION['auth'] == 'yes') {
			$this->setLogoutTime($_SESSION['user']);
			$_SESSION = array();
			session_destroy();
		}
	}
	
	// Returns true if user allready has access
	public function inSession() {
		if($_SESSION['auth'] == 'yes' && isset($_SESSION['user'])) { 
			return true;
		}
	}
	
	// Authorize user 
	public function authorize($user) {
		$_SESSION['user'] = $user;
		$_SESSION['auth'] = 'yes';
		$_SESSION['warnings'] = 0;
	}
	
	// Ban user if login attempts reaches 7
	public function banlist() {
		$sql = "SELECT ip FROM banlist 
				WHERE ip='".$_SERVER['REMOTE_ADDR']."'
				AND time >= DATE_SUB(NOW(), INTERVAL 1 HOUR)";
		
		$result = mysql_query($sql);
		if(!$result) {
			die('Invalid query: ' . mysql_error());
		}
		
		if(mysql_num_rows($result) > 0) {
			echo 'You are banned, try again in one hour';
			return true;
		} else {
			if($_SESSION['warnings'] > 5) {
				$this->banUser($_SERVER['REMOTE_ADDR']);
				$this->banlist();
			} else {
				return false;
			}
		}
		
	}
	
	// Notify user about login attempts left
	public function unauthorized() {
		$_SESSION['warnings']++;
		if($_SESSION['warnings'] >= 3) {
			$total = 7 - $_SESSION['warnings'];
			echo "$total attempts left";
		}
	}
	
	// Check to see if a session has expired
	public function expired() {
		if(isset($_SESSION['expire'])) {
			if((time() - $_SESSION['expire'] > 1800)) {
				$this->logout();
			} else {
				$_SESSION['expire'] = time();
			}
		} else {
			$_SESSION['expire'] = time();
		}
	}
}

?>